home *** CD-ROM | disk | FTP | other *** search
- Path: gate.net!pslfl2-24
- From: bhutto@gate.net (William Hutto)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers to structures
- Date: 3 Jan 1996 21:08:43 GMT
- Organization: CyberGate, Inc.
- Message-ID: <4cer8r$1v44@news.gate.net>
- References: <4cc9r4$m26@armitage.cyberspace.com> <4ccpgv$qpl@ixnews8.ix.netcom.com>
- NNTP-Posting-Host: pslfl2-24.gate.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- icarus@loomis (Tel Janin Aellinsar) wrote:
-
- >Berserker Dragon, Knights of the Cosmos icarus@BERKSHIRE.NET
-
- > I'm having trouble using a pointer to a struct. The idea is to
- > have a struct get filled by a function, which gets the address
- > and everything via function(struct type*). Very straightforward.
- > However, if I try to CHANGE anything in the struct, it just goes
- > back when the function is over. So, let's pretend this imaginary
- > structure is what I'm using:
- >
- > struct st1 {
- > char *name;
- > int yadda;
- > };
- >
- > And the function is:
- >
- > fn1(struct st1 *st)
-
- If you want to assigned values to be retained, this needs to be double
- indirection.
-
- void fn1(struct st1 **st)
-
- > {
- > st = (struct st1*)malloc(sizeof(struct st1*));
- ^^^^^^^^^^^
- This allocates enough space for a pointer, not your structure. Nor does it
- check validity before usage. This should be:
-
- if((*st=malloc(sizeof(struct st1))==NULL) {
- /*error*/
- }
-
- Also note the indirection: *st
-
- st points to the pointer that you pass to this function. That's where
- malloc()'s returned value is going.
-
- > st->name = (char*)malloc(16);
-
- if((*st->name=malloc(16))==NULL) {
- /*error*/
- }
-
- > strcpy(st->name,"Test");
-
- strcpy(*st->name,"Test");
-
- > st->yadda = 100;
-
- *st->yadda = 100;
-
- > }
-
- You must call this function with the address of a pointer of struct type.
-
- func()
- {
- struct st1 *stptr;
-
- fn1(&stptr);
- printf("%s, %d\n",stptr->name,stptr->yadda);
-
- }
-
- Hope that helps,
- Bill
-
- "Whatcha got on?...Your mind?"
-